package com.A21MobileSales;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.A21.Object.Global;
import com.A21MobileSales.DataBase.DatabaseHelper;
import com.A21MobileSales.JsonServices.Download;

public class InvoiceHistory extends Activity {

	DatabaseHelper ObjDBHelper;
	String title1, title2, function, Other, TrnType, TrnNo;
	Button btn_Home;
	ImageButton btn_back;
	TextView tv_Title1, tv_Title2;
	String strHTML = "";
	WebView wv;
	EditText FrmDate, ToDate;
 
	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.invoice_history);
		try {

			if (getIntent().hasExtra("title1")) {
				title1 = getIntent().getStringExtra("title1");
			}
			if (getIntent().hasExtra("title2")) {
				title2 = getIntent().getStringExtra("title2");
			}

			if (getIntent().hasExtra("function")) {
				function = getIntent().getStringExtra("function");
			}

			if (getIntent().hasExtra("Other")) {
				Other = getIntent().getStringExtra("Other");
			}

			FrmDate = (EditText) findViewById(R.id.edtFromDate);
			ToDate = (EditText) findViewById(R.id.edtToDate);

			wv = (WebView) findViewById(R.id.webview1);
			wv.getSettings().setBuiltInZoomControls(true);
			
			tv_Title1 = (TextView) findViewById(R.id.tv_Title1);
			tv_Title2 = (TextView) findViewById(R.id.tv_Title2);
			btn_Home = (Button) findViewById(R.id.btn_home);
			btn_Home.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent _intent = new Intent();
					_intent.setClass(InvoiceHistory.this, HomeScreen.class);
					startActivity(_intent);
				}
			});

			btn_back = (ImageButton) findViewById(R.id.btn_back);
			btn_back.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Bundle b = new Bundle();
					Intent _intent = new Intent();
					_intent.putExtras(b);
					if (function.equals("CI")) { 
						_intent.setClass(InvoiceHistory.this, CustomerMaster.class);
					} else{ 
						_intent.setClass(InvoiceHistory.this, ProductMaster.class);
					} 
					startActivity(_intent);
				}
			});
			tv_Title1.setText(title1);
			tv_Title2.setText(title2);

			Date DateDisp = new Date();
			final DateFormat dfDisp = new SimpleDateFormat("dd/MM/yyyy");
			FrmDate.setText(dfDisp.format(DateDisp));
			ToDate.setText(dfDisp.format(DateDisp));
			FrmDate.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Calendar mcurrentDate = Calendar.getInstance();
					int mYear = mcurrentDate.get(Calendar.YEAR);
					int mMonth = mcurrentDate.get(Calendar.MONTH);
					int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
					DatePickerDialog mDatePicker = new DatePickerDialog(
							InvoiceHistory.this,
							new DatePickerDialog.OnDateSetListener() {

								@Override
								public void onDateSet(DatePicker view,
										int year, int monthOfYear,
										int dayOfMonth) {

									String formatedDate = dfDisp.format(Global
											.getDate(year, monthOfYear,
													dayOfMonth));
									FrmDate.setText(formatedDate);
									
								}
							}, mYear, mMonth, mDay);
					mDatePicker.setTitle("Select date");
					mDatePicker.show();
				}
			});
			
			FrmDate.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					// TODO Auto-generated method stub

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
					// TODO Auto-generated method stub

				}

				@Override
				public void afterTextChanged(Editable s) { 
					new SyncTask().execute();
				}
			});

			ToDate.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Calendar mcurrentDate = Calendar.getInstance();
					int mYear = mcurrentDate.get(Calendar.YEAR);
					int mMonth = mcurrentDate.get(Calendar.MONTH);
					int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
					DatePickerDialog mDatePicker = new DatePickerDialog(
							InvoiceHistory.this,
							new DatePickerDialog.OnDateSetListener() {

								@Override
								public void onDateSet(DatePicker view,
										int year, int monthOfYear,
										int dayOfMonth) {
									String formatedDate = dfDisp.format(Global
											.getDate(year, monthOfYear,
													dayOfMonth));
									ToDate.setText(formatedDate);
									
								}
							}, mYear, mMonth, mDay);
					mDatePicker.setTitle("Select date");
					mDatePicker.show();
				}
			}); 
			
			ToDate.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					// TODO Auto-generated method stub

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
					// TODO Auto-generated method stub

				}

				@Override
				public void afterTextChanged(Editable s) { 
					new SyncTask().execute();
				}
			});
			 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
				 wv.getSettings().setAllowUniversalAccessFromFileURLs(true);
				 wv.getSettings().setAllowFileAccessFromFileURLs(true);
				 wv.getSettings().setJavaScriptEnabled(true);
			    }
			  
			final wvJavaScriptInterface javaScriptInterface = new wvJavaScriptInterface(
					this);
			wv.addJavascriptInterface(javaScriptInterface, "AndroidFunction");
			new SyncTask().execute();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	 
	public class wvJavaScriptInterface {
		Context mContext;

		wvJavaScriptInterface(Context c) {
			mContext = c;
		}
		
		@JavascriptInterface 
		public void ShowTrnDetail(String trnType, String trnNo) {
			TrnType = trnType;
			TrnNo = trnNo;  
			Intent intent = new Intent(InvoiceHistory.this, SimpleWebviewPopUp.class);
			Bundle bundle = new Bundle();
			bundle.putString("title1", "Invoice Details");
			bundle.putString("title2",TrnType +"-" +TrnNo);
			bundle.putString("TrnType", TrnType);
			bundle.putString("TrnNo", TrnNo);
			bundle.putString("function", "TrnDetails"); 
			intent.putExtras(bundle); 
		    startActivity(intent);
			
		}

	}

	private class SyncTask extends AsyncTask<String, Void, Void> {

		private ProgressDialog dialog = new ProgressDialog(InvoiceHistory.this);
		String StrMsg = null;

		protected void onPreExecute() {
			this.dialog.setMessage("Loading...");
			this.dialog.setCanceledOnTouchOutside(false);
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final String... a) {
			try {

				String strUserName = Global.getLoggedInUser().User;
				String strPassword = String
						.valueOf(Global.getLoggedInUser().strPassword);

				Download ObjDL = new Download(InvoiceHistory.this, strUserName,
						strPassword);

				if (function.equals("CI")) {
					strHTML=ObjDL.GetCustomerInvoiceHistory(Other,FrmDate.getText().toString().replace("/", ""),ToDate.getText().toString().replace("/", ""));
				} else if (function.equals("PI")) {

					strHTML=ObjDL.GetProductInvoiceHistory(Other,FrmDate.getText().toString().replace("/", ""),ToDate.getText().toString().replace("/", ""));
				} 
				StrMsg = "Success";
			} catch (Exception ex) {
				StrMsg = ex.getMessage();
			}
			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final Void unused) {

			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
				this.dialog = null;
			}
			try {
				if (StrMsg != null) {
					if (StrMsg.equals("Success")) {
						      
						 strHTML = "<link rel=\"stylesheet\" href=\"jquery.mobile-1.0.1.min.css\" /> " +
							 		"<script src=\"jquery-1.6.4.min.js\"></script> " +
							 		"<script src=\"jquery.mobile-1.0.1.min.js\"></script>" + strHTML; 
							 wv.loadDataWithBaseURL("file:///android_asset/", strHTML, "text/html", "UTF-8", null); 
						//wv.loadData(strHTML, "text/html", "UTF-8"); 
						
					} else {
						Toast.makeText(InvoiceHistory.this, StrMsg,
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(InvoiceHistory.this,
							"Please check the network connection!!!",
							Toast.LENGTH_SHORT).show();
				}

			} catch (Exception ex) {

				ex.printStackTrace();

			}

		}

	}

}